import React, { Fragment } from 'react';
import { connect } from 'umi';
import { ColumnsType } from 'antd/es/table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Table, Modal, message, Upload, Space } from 'antd';
import InvCheckModal from './InvCheckModal';
import InvCheckSearch from './InvCheckSearch';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';

interface User {
  key: number;
  partNum: string;
  warehouseCode: string;
  binNum: string;
  lotNum: string;
  onhandQty: string;
  avaQty: string;
}
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      visible: false,
      editStatus: false,
      formVals: {},
      dataSource: [],
      params: {},
      pageSize: 10,
      pageIndex: 1
    };
  }
  // componentDidMount，（装载完成），在render之后调用
  componentDidMount() {
    this.query();
  }
  query = () => {
    //数量盘点list 接口
    const { params = {}, pageSize, pageIndex } = this.state;
    const { dispatch } = this.props;
    this.setState({ loading: true });
    var skip = (pageIndex - 1) * pageSize;
    dispatch({
      type: 'Abp/getList',
      payload: {
        ...params,
        skipCount: skip,
        maxResultCount: pageSize
      },
      control: 'PartBin',
    }).then(() => {
      let resp = this.props.response;

      this.setState({ dataSource: resp.result?.items, totalCount: resp.result?.totalCount, loading: false });
    });
  };
  /**
   * 控制更新模态框显示
   * @param {boolean} visible 是否显示
   * @param {object} formVals 模态框默认值
   */
  switchVisible = (visible = false, formVals = {}, editStatus = false) => {
    this.setState({
      visible,
      formVals,
      editStatus,
    });
  };

  /**
   * 搜索
   */
  handleSearch = (values: any) => {
    const { warehouseCode, ...res } = values;
    this.setState(
      {
        params: {
          whseCode: warehouseCode,
          ...res,
        },
      },
      this.query,
    );
  };
  /**
   * 控制新增，编辑事件
   */
  handleSubmit = async (values: any) => {
    const { dispatch } = this.props;
    const { formVals, editStatus } = this.state;
    const { warehouseCode, onhandQty, ...res } = values;
    if (editStatus) {
      await dispatch({
        type: 'Abp/modify',
        payload: {
          id: formVals.id,
          ...values,
        },
        control: 'PartBin',
      });
    } else {
      await dispatch({
        type: 'Abp/addStock',
        payload: {
          qty: onhandQty,
          whseCode: warehouseCode,
          ...res,
        },
      });
    }

    this.switchVisible();
    this.query();
  };
  async handlerExport() {
    const { params } = this.state;
    var resp = await request('/api/Excel/ExportPartBin', {
      method: 'POST',
      params,
      responseType: 'blob',
    })
    var url = window.URL.createObjectURL(resp);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'Stock.xls';
    a.click();
  }
  handlerImport = (info: any) => {
    if (info.file.status === "done") {
      message.success("导入成功");
      this.query();
    }
  };
  render() {
    const { visible, formVals, editStatus, dataSource, loading, totalCount, pageSize } = this.state;
    let totOnhand = 0
    let totAva = 0
    dataSource.forEach((element: any) => {
      totOnhand += element.onhandQty
      totAva += element.avaQty
    });
    return (
      <PageHeaderWrapper title={false}>
        <Card title="库存盘点" extra={[
          <Space key='S1'>
            <Button htmlType="submit" onClick={() => this.switchVisible(true)}>
              新增
            </Button>
            <Button type="primary" onClick={() => this.handlerExport()}>
              导出
            </Button>
            <Upload
              accept=".xls,.xlsx,application/vnd.ms-excel"
              name='file'
              action="/api/Excel/ImportPartBin"
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              beforeUpload={UploadUtil.checkExcel}
              showUploadList={false}
              onChange={this.handlerImport}
            >
              <Button>导入</Button>
            </Upload>
          </Space>
        ]}>
          <InvCheckSearch onSearch={this.handleSearch}>

          </InvCheckSearch>
          <Table
            rowKey="id"
            loading={loading}
            dataSource={dataSource}
            columns={this.columns}
            scroll={{ x: '1600' }}
            size="small"            
            pagination={{
              onChange: (page,pageSize) => {
                this.setState({ pageIndex: page, pageSize }, () => {
                  this.query();
                });
              },
              pageSize,
              total: totalCount,
            }}
            summary={list => {
              let total = 0;
              let totalAva = 0;
              list.forEach(({ onhandQty, avaQty }) => {
                total += parseFloat(onhandQty.toString());
                totalAva += parseFloat(avaQty.toString());
              });

              return (
                <>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={0} colSpan={6} align="right">合计：</Table.Summary.Cell>
                    <Table.Summary.Cell index={5} align="center"><strong>{totOnhand.toFixed(2)}</strong></Table.Summary.Cell>
                    <Table.Summary.Cell index={6} align="center"><strong>{totAva.toFixed(2)}</strong></Table.Summary.Cell>
                    <Table.Summary.Cell index={7}></Table.Summary.Cell>
                  </Table.Summary.Row>
                </>
              );
            }}
          />
          <Modal
            title={editStatus ? '修改库存' : '创建库存'}
            width="640px"
            bodyStyle={{ padding: 24 }}
            visible={visible}
            destroyOnClose
            footer={null}
            onCancel={() => this.setState({ visible: false })}
          >
            <InvCheckModal
              formVals={formVals}
              editStatus={editStatus}
              onSubmit={this.handleSubmit}
            />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
  columns: ColumnsType<User> = [
    {
      title: '物料编码',
      dataIndex: 'partNum',
      align: 'center',
      width: 150,
    },
    {
      title: '描述',
      dataIndex: 'partDescription',
      ellipsis: true
    },
    {
      title: '单位',
      dataIndex: 'ium',
      width: 60,
    },
    {
      title: '仓库',
      align: 'center',
      dataIndex: 'warehouseCode',
      width: 150,
    },
    {
      title: '库位 ',
      align: 'center',
      dataIndex: 'binNum',
      width: 150,
    },
    {
      title: '批次',
      align: 'center',
      dataIndex: 'lotNum',
      width: 120,
    },
    {
      title: '现存数量',
      align: 'center',
      dataIndex: 'onhandQty',
      width: 120,
    },
    {
      title: '可用数量',
      align: 'center',
      dataIndex: 'avaQty',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_: any, record: any) => (
        <Fragment>
          <Button
            size="small"
            type="primary"
            title="编辑"
            onClick={() => this.switchVisible(true, { ...record }, true)}
          >
            编辑
          </Button>
        </Fragment>
      ),
    },
  ];
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
}))(ViewPage);
